const std = @import("std");
const rbtree = @import("rbtree");
const zlbmath = @import("zlbmath");
const dprint = std.debug.print;
test "mesh frame" {
    dprint("usize :{} u32:{}\n", .{ @sizeOf(usize), @sizeOf(u32) });
}

// test "mesh frame" {}
//

test "rbtree use" {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    // var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = arena.allocator();
    // const DefaultRbtree = rbtree.DefaultRBTree;

    const Tree = rbtree.DefaultRBTree(i32, f32);

    // tree.initFromSortedKVSlice
    // tree.initFromSortedSlice

    var tree = Tree.init(allocator, void{});
    defer tree.deinit();

    // insert some stuff into the tree
    var index: i32 = -19;
    while (index < 20) : (index += 1) {
        const value = std.math.pow(
            f32,
            0.5,
            @floatFromInt(index),
        );
        try tree.put(index, value);
    }
}
// const std = @import("std");
// const rbtree = @import("rbtree.zig"); // 假设库文件在路径中

// // 为测试创建一个简单的 Key-Value 类型
const Entry = struct {
    key: u32,
    value: []const u8,
};

// // 一个用于测试的已排序的 KV 对切片
const sorted_entries = [_]Entry{
    .{ .key = 1, .value = "one" },
    .{ .key = 2, .value = "two" },
    .{ .key = 3, .value = "three" },
    .{ .key = 5, .value = "five" },
    .{ .key = 8, .value = "eight" },
};

// 1. 测试：使用 `initFromSortedKVSlice` 从已排序的切片创建树
test "initFromSortedKVSlice" {
    const allocator = std.testing.allocator;
    const Tree = rbtree.DefaultRBTree(u32, []const u8);

    // 将 Entry 切片转换为 Tree.KV 切片
    var kv_slice: [sorted_entries.len]Tree.KV = undefined;
    for (sorted_entries, 0..) |entry, i| {
        kv_slice[i] = .{ .key = entry.key, .value = entry.value };
    }

    // 从已排序的 KV 切片创建红黑树
    var tree = try Tree.initFromSortedKVSlice(allocator, {}, // Context, 因为是 void
        &kv_slice);
    defer tree.deinit();

    // 验证树的大小
    try std.testing.expectEqual(sorted_entries.len, tree.count());

    // 验证可以正确找到所有键
    try std.testing.expect(tree.find(1) != null);
    try std.testing.expect(tree.find(2) != null);
    try std.testing.expect(tree.find(3) != null);
    try std.testing.expect(tree.find(5) != null);
    try std.testing.expect(tree.find(8) != null);

    // 验证找不到不存在的键
    try std.testing.expect(tree.find(4) == null);

    // 验证获取的值是正确的
    try std.testing.expectEqualStrings("three", tree.get(3).?);
    try std.testing.expectEqualStrings("eight", tree.get(8).?);
}

// // 2. 测试：验证树的顺序遍历（in-order traversal）
// test "in-order traversal of sorted tree" {
//     const allocator = std.testing.allocator;
//     const Tree = rbtree.DefaultRBTree(u32, []const u8);

//     var kv_slice: [sorted_entries.len]Tree.KV = undefined;
//     for (sorted_entries, 0..) |entry, i| {
//         kv_slice[i] = .{ .key = entry.key, .value = entry.value };
//     }

//     var tree = try Tree.initFromSortedKVSlice(allocator, undefined, &kv_slice);
//     defer tree.deinit();

//     // 使用迭代器按顺序访问所有节点
//     var iter = tree.kvIterator();
//     var expected_index: usize = 0;
//     while (iter.next()) |kv| {
//         try std.testing.expectEqual(sorted_entries[expected_index].key, kv.key);
//         try std.testing.expectEqualStrings(sorted_entries[expected_index].value, kv.value);
//         expected_index += 1;
//     }
//     // 确保遍历了所有元素
//     try std.testing.expectEqual(sorted_entries.len, expected_index);
// }

// // 3. 测试：在初始化后插入新元素
// test "insert after initFromSortedKVSlice" {
//     const allocator = std.testing.allocator;
//     const Tree = rbtree.DefaultRBTree(u32, []const u8);

//     var kv_slice: [sorted_entries.len]Tree.KV = undefined;
//     for (sorted_entries, 0..) |entry, i| {
//         kv_slice[i] = .{ .key = entry.key, .value = entry.value };
//     }

//     var tree = try Tree.initFromSortedKVSlice(allocator, undefined, &kv_slice);
//     defer tree.deinit();

//     // 在初始化后插入一个新元素
//     try tree.put(4, "four");

//     // 验证新元素已插入
//     try std.testing.expect(tree.find(4) != null);
//     try std.testing.expectEqualStrings("four", tree.get(4).?);

//     // 验证原元素仍然存在
//     try std.testing.expect(tree.find(3) != null);
//     try std.testing.expect(tree.find(5) != null);

//     // 验证总数增加了
//     try std.testing.expectEqual(sorted_entries.len + 1, tree.count());
// }

test "tets mesh" {
    var mesh = Mesh(f64, void, void, void, void, void).init(std.testing.allocator, {});
    defer mesh.deinit();

    // std.heap.smp_allocator;
    const v = mesh.create_vertexp(&.{ 0, 0, 0 });
    const v1 = mesh.create_vertexp(&.{ 0, 1, 0 });
    const v2 = mesh.create_vertexp(&.{ 0, 0, 1 });
    const v3 = mesh.create_vertexp(&.{ 0, 2.0, -1.0 });
    const v4 = mesh.create_vertexp(&.{ 0, -2.0, 1.0 });

    // var temp_v=[2]*Vertex{v.?,v1.?};
    // _ = mesh.create_facev(&.{ v.?, v1.? });
    const f1 = mesh.create_facev(&.{ v.?, v1.? });
    const f2 = mesh.create_facev(&.{ v1.?, v2.? });
    const f3 = mesh.create_facev(&.{ v2.?, v.? });
    const f4 = mesh.create_facev(&.{ v.?, v3.? });
    const f5 = mesh.create_facev(&.{ v3.?, v2.? });

    const hf1 = mesh.create_halfface(f1.?, &.{ v.?, v1.? });
    const hf2 = mesh.create_halfface(f2.?, &.{ v1.?, v2.? });
    const hf3 = mesh.create_halfface(f3.?, &.{ v2.?, v.? });
    _ = mesh.create_cellfn(&.{ hf1, hf2, hf3 });
    const hf4 = mesh.create_halfface(f4.?, &.{ v.?, v3.? });
    const hf5 = mesh.create_halfface(f5.?, &.{ v3.?, v2.? });
    const hf6 = mesh.create_halfface(f2.?, &.{ v2.?, v1.? });
    const hf7 = mesh.create_halfface(f1.?, &.{ v1.?, v.? });

    _ = mesh.create_cellfn(&.{ hf4, hf5, hf6, hf7 });
    const f6 = mesh.create_facev(&.{ v4.?, v.? });
    const f7 = mesh.create_facev(&.{ v2.?, v4.? });

    const hf8 = mesh.create_halfface(f6.?, &.{ v4.?, v.? });
    const hf9 = mesh.create_halfface(f3.?, &.{ v.?, v2.? });

    const hf10 = mesh.create_halfface(f7.?, &.{ v2.?, v4.? });

    _ = mesh.create_cellfn(&.{ hf8, hf9, hf10 });
    //
    const vv = mesh.create_vertexp(&.{ 10, 0, 0 });
    const vv1 = mesh.create_vertexp(&.{ 10, 1, 0 });
    const vv2 = mesh.create_vertexp(&.{ 10, 0, 1 });
    _ = mesh.create_cellv(&.{ vv.?, vv1.?, vv2.? });
    const a: i32 = blk: {
        break :blk 1 + 2;
    };
    dprint("a:{}\n", .{a});
    dprint("v id:{}\n", .{v.?.id});
    var v_iter = mesh.vertices.kvIterator();
    while (v_iter.next()) |kv| {
        dprint("v id:{}\n", .{kv.value.id});
    }
    dprint("num v:{} , num f:{},num c:{} num hf:{}\n", .{
        mesh.num_vertices(),
        mesh.num_faces(),
        mesh.num_cells(),
        mesh.num_halffaces(),
    });
}

pub fn Mesh(
    comptime P: type,
    comptime VT: type,
    comptime FT: type,
    comptime HFT: type,
    comptime CT: type,
    comptime MT: type,
) type {
    return struct {
        pub const Vertex = struct {
            // std.mem.indexOfAnyPos(comptime T: type, slice: []const T, start_index: usize, values: []const T)
            id: i32 = -1,
            cells: std.ArrayList(*Cell) = .empty,
            // 这里选择Arraylist是正确的，不要换成自己的数据结构。
            faces: std.ArrayList(*Face) = .empty,
            point: []P = &.{},
            prop: VT = VT{},
            pub fn init(vp: *Vertex) void {
                vp.id = -1;
                vp.cells = .empty;
                vp.faces = .empty;
                vp.point = &.{};
                vp.prop = VT{};
            }
            pub fn deinit(vp: *Vertex, allo: std.mem.Allocator) void {
                vp.cells.deinit(allo);
                vp.faces.deinit(allo);
                allo.free(vp.point);
                vp.point = &.{};
                vp.cells = .empty;
                vp.faces = .empty;
            }
            pub fn remove_c(vp: *Vertex, c: *const Cell) void {
                const i = std.mem.indexOfScalar(*const Cell, vp.cells.items, c) orelse return;
                // vp.cells.orderedRemove(i);
                _ = vp.cells.swapRemove(i);
                // swapRemove
            }
            pub fn remove_f(vp: *Vertex, f: *const Face) void {
                const i = std.mem.indexOfScalar(*const Face, vp.faces.items, f) orelse return;
                // vp.faces.orderedRemove(i);
                _ = vp.faces.swapRemove(i);
                // orderedRemove
            }
            // //孤立点也是边界点
            pub fn is_boundary(v: Vertex) bool {
                if (v.faces.len <= 0) {
                    return true;
                }
                for (v.faces.items) |f| {
                    if (f.*.is_boundary()) {
                        return true;
                    }
                }
                return false;
            }
            pub fn vv_begin(v: Vertex, allo: std.mem.Allocator) std.ArrayList(*Vertex) {
                var re: std.ArrayList(*Vertex) = .empty;
                for (v.faces.items) |f| {
                    for (f.vertices) |v1| {
                        if (v1.id == v.id) {
                            continue;
                        }
                        var mark: u32 = 0;
                        for (re.items) |v2| {
                            if (v2.id == v1.id) {
                                mark = 1;
                                break;
                            }
                        }
                        if (mark == 0) {
                            re.append(allo, v1) catch unreachable;
                        }
                    }
                }
                return re;
            }

            // pub fn is_manifold_vertex(v: *const Vertex) bool {

            // }
        };
        pub const HalfFace = struct {
            id: i32 = -1,
            vertices: []*Vertex = &.{},
            face: *Face,
            cell: ?*Cell = null,
            prop: HFT = HFT{},
            pub fn init(hf: *HalfFace) void {
                hf.id = -1;
                hf.vertices = &.{};
                // hf.face = null;
                hf.cell = null;
                hf.prop = HFT{};
            }
            pub fn deinit(hf: *HalfFace, allo: std.mem.Allocator) void {
                allo.free(hf.vertices);
                hf.vertices = &.{};
                // 注意：face 和 cell 是指针，不需要释放，只需置空
                // hf.face = null;
                hf.cell = null;
            }
            pub fn remove_c(hf: *HalfFace, c: *const Cell) void {
                if (hf.cell == c) {
                    hf.cell = null;
                }
            }
            pub fn opposite_halfface(hf: *HalfFace) *HalfFace {
                return if (hf.face.halffaces[0] == hf) &(hf.face.halffaces[1]) else &(hf.face.halffaces[0]);
            }
        };
        pub const Face = struct {
            id: i32 = -1,
            vertices: []*Vertex = &.{},
            halffaces: [2]HalfFace = [_]HalfFace{ HalfFace{ .face = undefined }, HalfFace{ .face = undefined } },
            prop: FT = FT{},
            pub fn init(fp: *Face) void {
                fp.id = -1;
                fp.vertices = &.{};
                fp.halffaces = [_]HalfFace{ HalfFace{ .face = fp }, HalfFace{ .face = fp } };
                fp.prop = FT{};
            }

            pub fn deinit(fp: *Face, allo: std.mem.Allocator) void {
                allo.free(fp.vertices);
                fp.vertices = &.{};
                // halffaces 是固定大小的数组，不需要释放
                // 但需要将指针置空
                fp.halffaces[0].deinit(allo);
                fp.halffaces[1].deinit(allo);
                fp.halffaces = [_]HalfFace{ HalfFace{ .face = fp }, HalfFace{ .face = fp } };
            }
            pub fn remove_c(fp: *Face, c: *const Cell) void {
                if (fp.halffaces[0].cell == c) {
                    fp.halffaces[0].cell = null;
                } else if (fp.halffaces[1].cell == c) {
                    fp.halffaces[1].cell = null;
                }
            }
            pub fn is_boundary(f: Face) bool {
                if (f.halffaces[0].cell == null or f.halffaces[1].cell == null) {
                    return true;
                }
                return false;
            }
        };
        pub const Cell = struct {
            id: i32 = -1,
            vertices: []*Vertex = &.{},
            halffaces: []*HalfFace = &.{},
            prop: CT = CT{},
            pub fn init(cp: *Cell) void {
                cp.id = -1;
                cp.vertices = &.{};
                cp.halffaces = &.{};
                cp.prop = CT{};
            }

            pub fn deinit(cp: *Cell, allo: std.mem.Allocator) void {
                allo.free(cp.vertices);
                cp.vertices = &.{};
                allo.free(cp.halffaces);
                cp.halffaces = &.{};
            }
            pub fn is_boundary(c: Cell) bool {
                for (c.halffaces) |hf| {
                    if (hf.face.*.is_boundary()) {
                        return true;
                    }
                }
                return false;
            }
            pub fn is_connected_with(c1: *const Cell, c2: *const Cell) bool {
                for (c1.halffaces) |hf| {
                    if (hf.opposite_halfface().cell == c2) {
                        return true;
                    }
                }
                return false;
            }
        };
        const Self = @This();
        allocator: std.mem.Allocator,
        // Int_RB_Tree *cells,*faces,*vertices,*halffaces;
        cells: rbtree.DefaultRBTree(i32, *Cell),
        faces: rbtree.DefaultRBTree(i32, *Face),
        vertices: rbtree.DefaultRBTree(i32, *Vertex),
        halffaces: rbtree.DefaultRBTree(i32, *HalfFace),

        cell_id: u32 = 0,
        vertex_id: u32 = 0,
        face_id: u32 = 0,
        halfface_id: u32 = 0,
        simplex: bool = true,

        dimension: u32 = 2,
        // Control delete operations and others
        manifold_require: bool = true,

        external_cells: std.DoublyLinkedList = std.DoublyLinkedList{},
        prop: MT = MT{},

        pub fn init(allocator: std.mem.Allocator, mprop: MT) Self {
            return Self{
                .allocator = allocator,
                .cells = rbtree.DefaultRBTree(i32, *Cell).init(allocator, {}),
                .vertices = rbtree.DefaultRBTree(i32, *Vertex).init(allocator, {}),
                .faces = rbtree.DefaultRBTree(i32, *Face).init(allocator, {}),
                .halffaces = rbtree.DefaultRBTree(i32, *HalfFace).init(allocator, {}),

                .cell_id = 0,
                .vertex_id = 0,
                .face_id = 0,
                .halfface_id = 0,
                .simplex = true,
                .dimension = 2,
                .manifold_require = true,
                .prop = mprop,
                .external_cells = std.DoublyLinkedList{},
            };
        }
        const CellNode = struct {
            data: Cell = .{},
            node: std.DoublyLinkedList.Node = .{},
        };
        pub fn deinit_external_cells(self: *Self) void {
            var it = self.external_cells.last;
            while (it) |itnode| {
                const l: *CellNode = @fieldParentPtr("node", itnode);
                // if (l.data) |c| {
                //     c.deinit(self.allocator);
                // }
                it = itnode.prev;
                self.allocator.destroy(l);
                // self.allocator.destroy(itnode.data);
                // self.allocator.destroy(itnode);
            }
            self.external_cells = std.DoublyLinkedList{};
        }

        pub fn external_cells_init_(self: *Self) void {
            self.deinit();
            self.external_cells = self.get_all_external_cells();
        }
        pub fn deinit(self: *Self) void {
            // self.external_cells.deinit();
            //
            var v_iter = self.vertices.kvIterator();
            while (v_iter.next()) |kv| {
                kv.value.deinit(self.allocator);
                self.allocator.destroy(kv.value);
            }

            // 释放所有面
            var f_iter = self.faces.kvIterator();
            while (f_iter.next()) |kv| {
                kv.value.deinit(self.allocator);
                self.allocator.destroy(kv.value);
            }

            // 释放所有半面
            // var hf_iter = self.halffaces.kvIterator();
            // while (hf_iter.next()) |kv| {
            //     kv.value.deinit(self.allocator);
            //     self.allocator.destroy(kv.value);
            // }

            // 释放所有单元
            var c_iter = self.cells.kvIterator();
            while (c_iter.next()) |kv| {
                kv.value.deinit(self.allocator);
                self.allocator.destroy(kv.value);
            }

            self.deinit_external_cells();
            self.vertices.deinit();
            self.cells.deinit();
            self.halffaces.deinit();
            self.faces.deinit();

            // self.allocator.destroy(ptr: anytype);

        }

        pub fn create_vertex(self: *Self) ?*Vertex {
            const re: *Vertex = self.allocator.create(Vertex) catch return null;
            // vertex_init(re);
            re.init();
            re.id = @intCast(self.vertex_id);
            self.vertices.put(re.id, re) catch {
                self.allocator.destroy(re);
                return null;
            };
            self.vertex_id += 1;

            return re;
        }
        pub fn create_vertexp(self: *Self, p: []const P) ?*Vertex {
            const re: *Vertex = self.allocator.create(Vertex) catch return null;
            // vertex_init(re);
            re.init();
            re.point = self.allocator.alloc(P, p.len) catch {
                self.allocator.destroy(re);
                return null;
            };
            @memmove(re.point, p);
            re.id = @intCast(self.vertex_id);
            self.vertices.put(re.id, re) catch {
                self.allocator.destroy(re);
                return null;
            };
            self.vertex_id += 1;

            return re;
        }
        // 创建面
        pub fn create_face(self: *Self) ?*Face {
            const re: *Face = self.allocator.create(Face) catch return null;
            re.init();
            re.id = @intCast(self.face_id);
            // 创建两个半面

            self.faces.put(re.id, re) catch {
                self.allocator.destroy(re);
                return null;
            };
            self.face_id += 1;
            return re;
        }

        // 创建单元
        pub fn create_cell(self: *Self) ?*Cell {
            const re: *Cell = self.allocator.create(Cell) catch return null;
            re.init();
            re.id = @intCast(self.cell_id);
            // 创建两个半面

            self.cells.put(re.id, re) catch {
                self.allocator.destroy(re);
                return null;
            };
            self.cell_id += 1;
            return re;
        }
        //如果返回NULL,意味创建失败
        pub fn create_halfface(self: *Self, f: *Face, temp_v: []const *Vertex) ?*HalfFace {
            if (f.halffaces[0].cell != null and f.halffaces[1].cell != null) {
                return null;
            }

            var hf: *HalfFace = undefined;

            if (f.halffaces[0].vertices.len == 0) {
                hf = &(f.halffaces[0]);
            } else if (f.halffaces[1].vertices.len == 0) {
                hf = &(f.halffaces[1]);
            } else {
                if (f.halffaces[0].cell == null) {
                    hf = &(f.halffaces[0]);
                } else if (f.halffaces[1].cell == null) {
                    hf = &(f.halffaces[1]);
                } else {
                    // printf("流形的网格拓扑错误\n");
                    // for(int i=0;i<size;i++)
                    // {
                    //     printf("%d ",temp_v[i]->id);
                    // }
                    // printf("\n");
                    return null;
                }
            }
            hf.id = @intCast(self.halfface_id);
            self.halffaces.put(hf.id, hf) catch {
                return null;
            };
            self.halfface_id += 1;
            if (hf.vertices.len == 0) {
                hf.vertices = self.allocator.alloc(*Vertex, temp_v.len) catch &.{};
            }
            @memmove(hf.vertices, temp_v);

            return hf;
        }
        //以下程序表明点到face的遍历不能保证顺(逆)时针(当cell是曲面)
        pub fn create_facev(self: *Self, temp_v: []const *Vertex) ?*Face {
            const f: *Face = get_facev(temp_v) orelse {
                const ff: *Face = self.create_face() orelse return null;
                ff.vertices = self.allocator.alloc(*Vertex, temp_v.len) catch &.{};
                // @memmove(ff.vertices, temp_v);
                for (0..ff.vertices.len) |i| {
                    ff.vertices[i] = temp_v[i];
                    ff.vertices[i].faces.append(self.allocator, ff) catch {
                        ff.deinit(self.allocator);
                        return ff;
                    };
                }
                return ff;
            };

            return f;
        }
        // 通过一组共面的半面创建单元。
        // 如果这组半面已经属于一个单元，则直接返回该单元。
        // 否则，创建一个新单元，并建立所有必要的拓扑链接。
        // 创建失败struct Mesh* own（如内存不足）时返回 null。
        pub fn create_cellf(self: *Self, temp_hf: []const *HalfFace) ?*Cell {
            // 1. 基本验证：如果传入的半面列表为空，无法创建单元。
            if (temp_hf.len == 0) {
                return null;
            }

            // 2. 检查是否已存在单元。
            // 假设如果第一个半面有单元，那么它就是我们想要的单元。
            // 一个更健壮的实现可以验证所有半面都属于同一个单元。
            if (temp_hf[0].cell) |existing_cell| {
                return existing_cell;
            }

            // 3. 创建一个新的 Cell 对象。如果失败，直接返回 null。
            const c: *Cell = self.create_cell() orelse return null;

            c.halffaces = self.allocator.alloc(*HalfFace, temp_hf.len) catch {
                // 回滚：内存分配失败，销毁刚刚创建的空 Cell。
                _ = self.cells.remove(c.id);
                self.allocator.destroy(c);

                return null;
            };
            // 5. 收集所有唯一的顶点。
            // 使用 ArrayList 作为临时容器，是 Zig 中处理动态数量元素的标准做法。
            var uni_v_len: usize = 0;

            for (temp_hf) |hf| {
                uni_v_len += hf.vertices.len;
            }
            // temp_hf.len/2;
            var buffer: [200]*Vertex = undefined;

            var unique_vertices = std.ArrayList(*Vertex).initBuffer(&buffer);
            if (uni_v_len > 200) {
                const buffer1 = self.allocator.alloc(*Vertex, uni_v_len) catch return null;
                unique_vertices = std.ArrayList(*Vertex).initBuffer(buffer1);
            }
            defer {
                if (uni_v_len > 200) {
                    unique_vertices.deinit(self.allocator);
                }
            }

            for (0..temp_hf.len) |i| {
                c.halffaces[i] = temp_hf[i];
                temp_hf[i].cell = c;
                for (temp_hf[i].vertices) |v| {
                    if (std.mem.indexOfScalar(*Vertex, unique_vertices.items, v) == null) {
                        // 如果不存在，则添加。如果追加失败（内存不足），执行回滚。
                        unique_vertices.appendAssumeCapacity(v);
                        // unique_vertices.append(self.allocator, v) catch continue;
                    }
                }
            }
            c.vertices = self.allocator.alloc(*Vertex, unique_vertices.items.len) catch &.{};
            @memmove(c.vertices, unique_vertices.items);
            // c.vertices = unique_vertices.toOwnedSlice(self.allocator) catch &.{};
            for (c.vertices) |v| {
                v.cells.append(self.allocator, c) catch continue;
                // v.cell = c;
            }
            return c;
        }
        pub fn create_cellfn(self: *Self, temp_hf: []const ?*HalfFace) ?*Cell {
            for (temp_hf) |hf| {
                if (hf == null) {
                    if (self.manifold_require) {
                        for (temp_hf) |hf1| {
                            if (hf1) |hf1p| {
                                const f = hf1p.face;
                                _ = self.delete_halfface_internal(hf1p.*, true);
                                if (f.halffaces[0].cell == null and f.halffaces[1].cell == null) {
                                    _ = self.delete_face_internal(f.*, true);
                                }
                            }
                        }
                    }
                    return null;
                }
            }
            if (temp_hf.len == 0) {
                return null;
            }

            // 2. 检查是否已存在单元。
            // 假设如果第一个半面有单元，那么它就是我们想要的单元。
            // 一个更健壮的实现可以验证所有半面都属于同一个单元。
            if (temp_hf[0].?.cell) |existing_cell| {
                return existing_cell;
            }

            // 3. 创建一个新的 Cell 对象。如果失败，直接返回 null。
            const c: *Cell = self.create_cell() orelse return null;

            c.halffaces = self.allocator.alloc(*HalfFace, temp_hf.len) catch {
                // 回滚：内存分配失败，销毁刚刚创建的空 Cell。
                _ = self.cells.remove(c.id);
                self.allocator.destroy(c);

                return null;
            };
            // 5. 收集所有唯一的顶点。
            // 使用 ArrayList 作为临时容器，是 Zig 中处理动态数量元素的标准做法。
            var uni_v_len: usize = 0;

            for (temp_hf) |hf| {
                if (hf) |hfp| {
                    uni_v_len += hfp.vertices.len;
                }
            }
            // temp_hf.len/2;
            var buffer: [200]*Vertex = undefined;

            var unique_vertices = std.ArrayList(*Vertex).initBuffer(&buffer);
            if (uni_v_len > 200) {
                const buffer1 = self.allocator.alloc(*Vertex, uni_v_len) catch return null;
                unique_vertices = std.ArrayList(*Vertex).initBuffer(buffer1);
            }
            defer {
                if (uni_v_len > 200) {
                    unique_vertices.deinit(self.allocator);
                }
            }

            // defer unique_vertices.deinit(self.allocator);

            for (0..temp_hf.len) |i| {
                c.halffaces[i] = temp_hf[i].?;
                c.halffaces[i].cell = c;
                for (c.halffaces[i].vertices) |v| {
                    if (std.mem.indexOfScalar(*Vertex, unique_vertices.items, v) == null) {
                        // 如果不存在，则添加。如果追加失败（内存不足），执行回滚。
                        unique_vertices.appendAssumeCapacity(v);
                        // unique_vertices.append(self.allocator, v) catch continue;
                    }
                }
            }

            c.vertices = self.allocator.alloc(*Vertex, unique_vertices.items.len) catch &.{};
            @memmove(c.vertices, unique_vertices.items);
            // unique_vertices.toOwnedSlice(self.allocator) catch &.{};

            for (c.vertices) |v| {
                v.cells.append(self.allocator, c) catch continue;
                // v.cell = c;
            }
            return c;
        }
        pub fn create_cellv(self: *Self, temp_v: []const *Vertex) ?*Cell {
            const ccc = get_cellv(temp_v);
            if (ccc) |cc| {
                return cc;
            }

            const hfs = self.allocator.alloc(*HalfFace, temp_v.len) catch return null;
            var buffer = [_]*Vertex{undefined} ** 200;
            // var temp_v1: []*Vertex = undefined;
            var temp_v1: []*Vertex = buffer[0..200];

            if (temp_v.len - 1 > 200) {
                temp_v1 = self.allocator.alloc(*Vertex, temp_v.len - 1) catch {
                    self.allocator.free(hfs);
                    return null;
                };
                // defer self.allocator.free(temp_v1);
            } else {
                temp_v1 = buffer[0..(temp_v.len - 1)];
            }
            defer {
                if (temp_v.len - 1 > 200) {
                    self.allocator.free(temp_v1);
                }
            }

            // const temp_v1: []*Vertex = self.allocator.alloc(*Vertex, temp_v.len - 1) catch {
            //     self.allocator.free(hfs);
            //     return null;
            // };
            // defer self.allocator.free(temp_v1);

            for (0..temp_v.len) |i| {
                var temp_i: usize = 0;
                //     vec.size=0;
                for (0..temp_v.len) |j| {
                    if (j != i) {
                        temp_v1[temp_i] = temp_v[j];
                        temp_i += 1;
                    }
                }
                if ((temp_v.len - i - 1) % 2 == 0) {} else if (temp_v.len > 2) {
                    const vv = temp_v1[0];
                    temp_v1[0] = temp_v1[1];
                    temp_v1[1] = vv;
                }

                const f: ?*Face = self.create_facev(temp_v1);
                const hf: ?*HalfFace = if (f == null) null else self.create_halfface(f.?, temp_v1);
                if (hf) |hfp| {
                    hfs[i] = hfp;
                } else {
                    if (self.manifold_require) {
                        for (0..i) |j| {
                            // hfs[j].id;
                            _ = self.delete_halfface_internal(hfs[j].*, true);
                            if (hfs[j].face.halffaces[0].cell == null and hfs[j].face.halffaces[1].cell == null) {
                                _ = self.delete_face_internal(hfs[j].face.*, true);
                            }
                        }
                        if (f) |fp| {
                            if (fp.halffaces[0].cell == null and fp.halffaces[1].cell == null) {
                                _ = self.delete_face_internal(fp.*, true);
                            }
                        }
                    }

                    // self.allocator.free(temp_v1);
                    self.allocator.free(hfs);
                    return null;
                }
            }
            // self.allocator.free(temp_v1);
            // vec.clear(&vec);
            const c = self.create_cell() orelse return null;

            c.halffaces = hfs;
            c.vertices = self.allocator.alloc(*Vertex, temp_v.len) catch return c;

            for (0..temp_v.len) |i| {
                c.vertices[i] = temp_v[i];
                temp_v[i].cells.append(self.allocator, c) catch continue;
                hfs[i].cell = c;
            }
            return c;
        }
        fn delete_cell_internal(self: *Self, c_: Cell, burning: bool) bool {
            const node = self.cells.find(c_.id) orelse return false;
            const c: *Cell = node.value;
            self.cells.removeNode(node);
            // const c: *Cell = self.cells.get(c_.id) orelse return false;
            // const re = self.cells.remove(c.id);
            //
            for (c.halffaces) |hf| {
                hf.remove_c(c);
                _ = self.halffaces.remove(hf.id);
            }
            for (c.vertices) |v| {
                v.remove_c(c);
            }
            if (burning) {
                c.deinit(self.allocator);
                self.allocator.destroy(c);
            }
            return true;
        }
        fn delete_halfface_internal(self: *Self, hf_: HalfFace, burning: bool) bool {
            // const hf: *HalfFace = self.halffaces.get(hf_.id) orelse return false;
            // const re = self.halffaces.remove(hf.id);
            const node = self.halffaces.find(hf_.id) orelse return false;
            const hf = node.value;
            self.halffaces.removeNode(node);

            if (hf.cell) |c| {
                _ = self.delete_cell_internal(c.*, burning);
            }

            if (burning) {
                self.allocator.free(hf.vertices);
                hf.vertices = &.{};
                hf.cell = null;
                //这里不要 hf.deinit(self.allocator);
                // 这里不用destroy(hf);
            }
            return true;
        }
        fn delete_face_internal(self: *Self, f_: Face, burning: bool) bool {
            // const f: *Face = self.faces.get(f_.id) orelse return false;
            // const re = self.faces.remove(f.id);
            const node = self.faces.find(f_.id) orelse return false;
            const f = node.value;
            self.faces.removeNode(node);

            _ = self.delete_halfface_internal(f.halffaces[0], burning);
            _ = self.delete_halfface_internal(f.halffaces[1], burning);
            for (f.vertices) |v| {
                v.remove_f(f);
            }
            if (burning) {
                f.deinit(self.allocator);
                self.allocator.destroy(f);
            }
            return true;
        }
        fn delete_vertex_internal(self: *Self, v_: Vertex, burning: bool) bool {
            // const v: *Vertex = self.vertices.get(v_.id) orelse return false;
            // const re = self.vertices.remove(v.id);
            const node = self.vertices.find(v_.id) orelse return false;
            const v = node.value;
            self.vertices.removeNode(node);

            while (v.faces.items.len > 0) {
                self.delete_face_internal(v.faces.items[0], burning);
            }
            if (burning) {
                v.deinit(self.allocator);
                self.allocator.destroy(v);
            }
            return true;
        }
        pub fn delete_cell(self: *Self, c_: Cell, burning: bool) bool {
            if (!self.manifold_require) {
                return self.delete_cell_internal(c_, burning);
            } else {
                const node = self.cells.find(c_.id) orelse return false;
                const c: *Cell = node.value;
                self.cells.removeNode(node);
                // const c: *Cell = self.cells.get(c_.id) orelse return false;
                // const re = self.cells.remove(c.id);
                //
                for (c.halffaces) |hf| {
                    hf.remove_c(c);
                    _ = self.halffaces.remove(hf.id);
                }
                for (c.vertices) |v| {
                    v.remove_c(c);
                }
                // 遍历面，查看是否
                for (c.halffaces) |hf| {
                    const f = hf.face.?;
                    if (f.halffaces[0].cell == null and f.halffaces[1].cell == null) {
                        for (f.vertices) |v| {
                            v.remove_f(f);
                        }
                        self.halffaces.remove(f.halffaces[0].id);
                        self.halffaces.remove(f.halffaces[1].id);
                        self.faces.remove(f.id);
                        if (burning) {
                            f.deinit(self.allocator);
                            self.destroy(f);
                        }
                    }
                }
                if (burning) {
                    c.deinit(self.allocator);
                    self.allocator.destroy(c);
                }
                return true;
            }
            return true;
        }

        fn delete_halfface(self: *Self, hf_: HalfFace, burning: bool) bool {
            if (!self.manifold_require) {
                self.delete_halfface_internal(hf_, burning);
            } else {
                var hf = self.halffaces.get(hf_.id) orelse return false;
                if (hf.cell) |c| {
                    self.delete_cell(c, burning);
                }
                const node = self.halffaces.find(hf_.id) orelse return false;
                hf = node.value;
                self.halffaces.remodeNode(node);

                if (burning) {
                    self.allocator.free(hf.vertices);
                    hf.vertices = &.{};
                    hf.cell = null;
                }
                return true;
            }
            return true;
        }
        fn delete_face(self: *Self, f_: Face, burning: bool) bool {
            if (!self.manifold_require) {
                return self.delete_face_internal(f_, burning);
            } else {
                var f = self.faces.get(f_.id) orelse return false;

                _ = self.delete_halfface(&(f.halffaces[0]), burning);
                f = self.faces.get(f_.id) orelse return false;

                _ = self.delete_halfface(&(f.halffaces[1]), burning);
                const node = self.faces.find(f_.id) orelse return false;
                f = node.value;
                self.faces.removeNode(node);
                if (burning) {
                    f.deinit(self.allocator);
                    self.allocator.destroy(f);
                }
                return true;
            }

            return true;
        }

        fn delete_vertex(self: *Self, v_: Vertex, burning: bool) bool {
            const node = self.vertices.find(v_.id) orelse return false;
            const v = node.value;
            self.vertices.removeNode(node);

            while (v.faces.items.len > 0) {
                self.delete_face(v.faces.items[0], burning);
            }
            if (burning) {
                v.deinit(self.allocator);
                self.allocator.destroy(v);
            }
        }

        // 获取顶点指针
        pub fn get_vertexp(self: *Self, id: i32) ?*Vertex {
            return self.vertices.get(id);
        }

        // 获取单元指针
        pub fn get_cellp(self: *Self, id: i32) ?*Cell {
            return self.cells.get(id);
        }
        // 获取面指针
        pub fn get_facep(self: *Self, id: i32) ?*Face {
            return self.faces.get(id);
        }

        // 获取半面指针
        pub fn get_halffacep(self: *Self, id: i32) ?*HalfFace {
            return self.halffaces.get(id);
        }
        // 获取顶点（返回副本）
        pub fn get_vertex(self: *Self, id: i32) Vertex {
            if (self.get_vertexp(id)) |v| {
                return v.*;
            }
            var v: Vertex = .{};
            v.init();
            return v;
        }
        // 获取单元（返回副本）
        pub fn get_cell(self: *Self, id: i32) Cell {
            if (self.get_cellp(id)) |c| {
                return c.*;
            }
            var c: Cell = .{};
            c.init();
            return c;
        }

        // 获取面（返回副本）
        pub fn get_face(self: *Self, id: i32) Face {
            if (self.get_facep(id)) |f| {
                return f.*;
            }
            var f: Face = .{};
            f.init();
            return f;
        }
        // 获取半面（返回副本）
        pub fn get_halfface(self: *Self, id: i32) HalfFace {
            if (self.get_halffacep(id)) |hf| {
                return hf.*;
            }
            var hf: HalfFace = .{};
            hf.init();
            return hf;
        }
        // 通过顶点查找面
        pub fn get_facev(vertices: []const *Vertex) ?*Face {
            if (vertices.len == 0) return null;

            for (vertices[0].faces.items) |face| {
                var found = true;

                for (vertices[1..]) |v| {
                    var has_face = false;
                    for (v.faces.items) |vf| {
                        if (vf == face) {
                            has_face = true;
                            break;
                        }
                    }

                    if (!has_face) {
                        found = false;
                        break;
                    }
                }

                if (found) {
                    return face;
                }
            }

            return null;
        }
        // 通过顶点查找单元
        pub fn get_cellv(vertices: []const *Vertex) ?*Cell {
            if (vertices.len == 0) return null;

            for (vertices[0].cells.items) |cell| {
                var found = true;

                for (vertices[1..]) |v| {
                    var has_cell = false;
                    for (v.cells.items) |vc| {
                        if (vc == cell) {
                            has_cell = true;
                            break;
                        }
                    }

                    if (!has_cell) {
                        found = false;
                        break;
                    }
                }

                if (found) {
                    return cell;
                }
            }

            return null;
        }
        // 通过面查找单元
        pub fn get_cellf(faces: []const *Face) ?*Cell {
            if (faces.len == 0) return null;

            for (faces[0].halffaces) |hf| {
                if (hf.cell) |cell| {
                    var found = true;

                    for (faces[1..]) |f| {
                        var has_cell = false;
                        for (f.halffaces) |fhf| {
                            if (fhf.cell == cell) {
                                has_cell = true;
                                break;
                            }
                        }

                        if (!has_cell) {
                            found = false;
                            break;
                        }
                    }

                    if (found) {
                        return cell;
                    }
                }
            }

            return null;
        }
        // 获取顶点数量
        pub fn num_vertices(self: *Self) usize {
            return self.vertices.count();
        }
        // 获取面数量
        pub fn num_faces(self: *Self) usize {
            return self.faces.count();
        }

        // 获取单元数量
        pub fn num_cells(self: *Self) usize {
            return self.cells.count();
        }

        // 获取半面数量
        pub fn num_halffaces(self: *Self) usize {
            return self.halffaces.count();
        }

        //给它一个初始面，他会返回boundary的node链.这种寻找边界的方式.
        //返回半边
        //用红黑树RB_Tree做标记，代替prop
        //不确保保持流形

        /// 这个是不是需要配个单独的allocator?
        pub fn boundary_halffaces(self: *const Self, f_: ?*Face) std.ArrayList(*HalfFace) {
            // 1. 初始化返回列表、DFS栈和用于标记已访问面的红黑树
            var boundary_hfs: std.ArrayList(*HalfFace) = .empty;
            if (f_ == null or !f_.?.is_boundary()) {
                return boundary_hfs;
            }
            const f: *Face = self.faces.get(f_.?.id) orelse return boundary_hfs;
            var stack: std.ArrayList(*Face) = .empty;
            // 遵循C代码注释的要求，使用红黑树做标记
            var visited_faces: rbtree.DefaultRBTree(i32, void) = rbtree.DefaultRBTree(i32, void).init(self.allocator, {});

            // 2. 使用 defer 确保临时数据结构在函数退出时被释放
            defer stack.deinit(self.allocator);
            defer visited_faces.deinit();
            // 5. 设置DFS的起点
            // 将起始面压入栈并标记为已访问
            stack.append(self.allocator, f) catch return boundary_hfs;
            visited_faces.put(f.id, {}) catch return boundary_hfs;

            // 将起始面的边界半面添加到结果列表中
            if (f.halffaces[0].cell == null) {
                boundary_hfs.append(self.allocator, &f.halffaces[0]) catch return boundary_hfs;
            } else { // 已经检查过 is_boundary()，所以另一个必然是
                boundary_hfs.append(self.allocator, &f.halffaces[1]) catch return boundary_hfs;
            }
            // 6. 执行深度优先搜索（DFS）
            // 这个循环结构精确地模仿了C代码中 `goto push;` 的逻辑
            while (stack.items.len > 0) {
                const current_f = stack.items[stack.items.len - 1]; // "Peek" at the stack top
                var found_new_path = false;

                // 确定内部的半面，以便通过它的顶点找到邻接面
                const inner_hf = if (current_f.halffaces[0].cell != null)
                    &current_f.halffaces[0]
                else
                    &current_f.halffaces[1];

                // 逆序遍历顶点，以匹配C代码的顺序
                var i: usize = inner_hf.vertices.len;
                while (i > 0) {
                    i -= 1;
                    const v = inner_hf.vertices[i];

                    // 遍历当前顶点的所有邻接面
                    for (v.faces.items) |neighbor_f| {
                        // 如果邻接面是边界且未被访问过
                        if (neighbor_f.is_boundary() and !visited_faces.contains(neighbor_f.id)) {
                            // 标记为已访问
                            visited_faces.put(neighbor_f.id, {}) catch return boundary_hfs;

                            // 将其边界半面添加到结果列表
                            if (neighbor_f.halffaces[0].cell == null) {
                                boundary_hfs.append(&neighbor_f.halffaces[0]) catch return boundary_hfs;
                            } else {
                                boundary_hfs.append(&neighbor_f.halffaces[1]) catch return boundary_hfs;
                            }

                            // 将新发现的面压入栈
                            stack.append(self.allocator, neighbor_f) catch return boundary_hfs;

                            // 设置标志并跳出内层循环，以模拟 'goto push'
                            found_new_path = true;
                            break;
                        }
                    }
                    if (found_new_path) {
                        break;
                    }
                }

                if (found_new_path) {
                    // 'goto push': 立即开始处理新压入栈顶的面
                    continue;
                } else {
                    // 如果当前面的所有邻居都已探索完毕，则将其从栈中弹出
                    _ = stack.pop();
                }
            }
            return boundary_hfs;
        }
        fn one_dim_boundary(self: *const Self) std.ArrayList(*HalfFace) {
            var arr: std.ArrayList(*Face) = .empty;
            var iter = self.f_begin();
            while (iter.next()) |kv| {
                if (kv.value.halffaces[0].cell == null) {
                    arr.append(self.allocator, kv.value.halffaces[0]) catch unreachable;
                }
                if (kv.value.halffaces[1].cell == null) {
                    arr.append(self.allocator, kv.value.halffaces[1]) catch unreachable;
                }
            }

            return arr;
        }
        pub fn c_begin(self: *const Self) rbtree.DefaultRBTree(i32, *Cell).KVIterator {
            return self.cells.kvIterator();
        }
        pub fn v_begin(self: *const Self) rbtree.DefaultRBTree(i32, *Vertex).KVIterator {
            return self.vertices.kvIterator();
        }
        pub fn f_begin(self: *const Self) rbtree.DefaultRBTree(i32, *Face).KVIterator {
            return self.faces.kvIterator();
        }
        pub fn hf_begin(self: *const Self) rbtree.DefaultRBTree(i32, *HalfFace).KVIterator {
            return self.halffaces.kvIterator();
        }

        fn my_fill_extern_cell_from_one_face(
            self: *Self,
            f: *const Face,
            tree: rbtree.DefaultRBTree(i32, *Face),
            c: *Cell,
        ) !void {
            var arr_halffaces = boundary_halffaces(self, f);
            defer arr_halffaces.deinit(self.allocator);

            if (arr_halffaces.items.len <= 0) {
                return;
            }
            c.halffaces = arr_halffaces.toOwnedSlice(self.allocator);
            if (self.dimension == 2) {
                c.vertices = try self.allocator.alloc(*Vertex, c.halffaces.len);
            }

            for (c.halffaces, 0..) |hf, i| {
                tree.put(hf.face.id, hf.face);
                const hf1 = hf.opposite_halfface();
                if (hf.vertices.len <= 0) {
                    hf.vertices = try self.allocator.alloc(*Vertex, hf1.vertices.len);
                }
                @memmove(hf.vertices, hf1.vertices);
                if (hf.vertices.len >= 2) {
                    const temp = hf.vertices[0];
                    hf.vertices[0] = hf.vertices[1];
                    hf.vertices[1] = temp;
                }
                if (self.dimension == 2) {
                    c.vertices[i] = hf.vertices[0];
                }
            }
        }
        fn get_all_external_cells(self: *Self) std.DoublyLinkedList {
            // Node* re=NULL;
            var re = std.DoublyLinkedList{};
            if (self.dimension == 1) {
                var halffaces = one_dim_boundary(self);
                if (halffaces.items.len <= 0) {
                    return re;
                }
                // var c = self.allocator.create(Cell);
                // c.init();
                var l = self.allocator.create(CellNode);
                l.data.init();
                l.data.halffaces = halffaces.toOwnedSlice(self.allocator);
                l.node = .{ .prev = null, .next = null };
                re.append(&(l.node));
                return re;
            }
            // Int_RB_Tree* tree=(Int_RB_Tree*)malloc(sizeof(Int_RB_Tree));
            // int_rb_tree_init(tree);
            var tree: rbtree.DefaultRBTree(i32, void) = rbtree.DefaultRBTree(i32, void).init(self.allocator, {});

            defer tree.deinit();
            // for(auto it=Mesh_f_beginn(own);it!=Mesh_f_endn(own);it++)
            var iter = self.f_begin();
            while (iter.next()) |kv| {
                if (kv.value.is_boundary() and !tree.contains(kv.key)) {
                    var l = self.allocator.create(CellNode);
                    l.data.init();
                    self.my_fill_extern_cell_from_one_face(kv.value, tree, &(l.data));
                    l.node = .{ .prev = null, .next = null };

                    re.append(&(l.node));
                }
            }

            return re;
        }

        pub fn isManifold(self: *const Self, v: *const Vertex) bool {
            if (v.cells.items.len == 0) {
                return self.dimension == 0;
            }
            for (v.faces.items) |f| {
                if (f.halffaces[0].cell == null and f.halffaces[1].cell == null) {
                    return false;
                }
            }
            var buffer1: [200]*Cell = undefined;
            var buffer2: [200]*Cell = undefined;

            var connected_cells = std.ArrayList(*Cell).initBuffer(&buffer1);
            // defer connected_cells.deinit(self.allocator);

            var remaining_cells = std.ArrayList(*Cell).initBuffer(&buffer2);
            if (v.cells.items.len > 200) {
                const buffer11 = self.allocator.alloc(*Cell, v.cells.items.len) catch return false;
                const buffer22 = self.allocator.alloc(*Cell, v.cells.items.len) catch return false;
                connected_cells = std.ArrayList(*Cell).initBuffer(buffer11);
                remaining_cells = std.ArrayList(*Cell).initBuffer(buffer22);
            }
            defer {
                if (v.cells.items.len > 200) {
                    connected_cells.deinit(self.allocator);
                    remaining_cells.deinit(self.allocator);
                }
            }
            // defer remaining_cells.deinit(self.allocator);

            // Initialize connected_cells with the first cell and remaining_cells with the rest
            connected_cells.appendAssumeCapacity(v.cells.items[0]);
            remaining_cells.appendSliceAssumeCapacity(v.cells.items[1..]);

            var changed: bool = true;
            while (changed) {
                changed = false;
                // var i = remaining_cells.items.len;
                for (0..remaining_cells.items.len) |i| {
                    const current_cell = remaining_cells.items[i];
                    // var is_connected = false;
                    for (connected_cells.items) |connected_cell| {
                        if (current_cell.is_connected_with(connected_cell)) {
                            // is_connected = true;
                            connected_cells.appendAssumeCapacity(current_cell);
                            _ = remaining_cells.swapRemove(i);
                            changed = true;
                            break;
                        }
                    }
                    if (changed) {
                        break;
                    }
                }
            }
            return remaining_cells.items.len == 0;
        }
        pub fn rearrange_elements_id(self: *Self) void {
            var i: i32 = 0;
            var current = self.vertices.findMin();
            while (current) |c| : (current = c.next()) {
                c.key = i;
                c.value.id = i;
                i += 1;
                // std.debug.print("Node {} -> {}\n", .{ c.key, c.value });
            }
            i = 0;
            current = self.faces.findMin();
            while (current) |c| : (current = c.next()) {
                c.key = i;
                c.value.id = i;
                i += 1;
                // std.debug.print("Node {} -> {}\n", .{ c.key, c.value });
            }
            i = 0;
            current = self.halffaces.findMin();
            while (current) |c| : (current = c.next()) {
                c.key = i;
                c.value.id = i;
                i += 1;
                // std.debug.print("Node {} -> {}\n", .{ c.key, c.value });
            }
            i = 0;
            current = self.cells.findMin();
            while (current) |c| : (current = c.next()) {
                c.key = i;
                c.value.id = i;
                i += 1;
                // std.debug.print("Node {} -> {}\n", .{ c.key, c.value });
            }
        }
        pub fn non_manifold_vertices(self: *const Self) std.ArrayList(*Vertex) {
            var re: std.ArrayList(*Vertex) = .empty;
            var it = self.vertices.kvIterator();
            while (it.next()) |entry| {
                if (!self.isManifold(entry.value)) {
                    re.append(self.allocator, entry.value) catch unreachable;
                }
            }
            return re;
        }

        pub const IteratorEdge = struct {
            f: ?*Face,
            v: ?*Vertex,
            mark: ?*Face,

            pub fn init() IteratorEdge {
                return .{
                    .f = null,
                    .v = null,
                    .mark = null,
                };
            }

            pub fn next(ie: *IteratorEdge) ?*Face {
                if (ie.v == null or ie.f == null) {
                    ie.f = null;
                    ie.v = null;
                    return ie.f;
                }

                const current_f = ie.f.?;
                const current_v = ie.v.?;

                // Find the other vertex in the current face (edge)
                var next_v: ?*Vertex = null;
                for (current_f.vertices.items) |v_in_f| {
                    if (v_in_f != current_v) {
                        next_v = v_in_f;
                        break;
                    }
                }

                ie.v = next_v;
                if (next_v == null) {
                    // This can happen if the face has only one vertex, which is unusual.
                    // Or if we've completed a loop and are stopping.
                    ie.f = null;
                    return ie.f;
                }

                // Find the next face connected to next_v, which is not the current face
                var next_f: ?*Face = null;
                for (next_v.?.faces.items) |f_on_v| {
                    if (f_on_v != current_f) {
                        next_f = f_on_v;
                        break;
                    }
                }

                ie.f = next_f;

                // If we have looped back to the starting face, end the iteration.
                if (ie.f == ie.mark) {
                    ie.v = null;
                    ie.f = null;
                }
                return ie.f;
            }
        };

        pub fn edge_begin(self: *Self, v_start: *Vertex, f_start: *Face) IteratorEdge {
            _ = self; // self is not used in this implementation but is kept for method consistency
            var ie = IteratorEdge.init();

            // The C code seems to re-fetch pointers, but in Zig we can just use the provided ones.
            // We assume v_start and f_start are valid pointers from the mesh.
            ie.v = v_start;
            ie.f = f_start;
            ie.mark = f_start;

            return ie;
        }
    };
}

pub const Mesh_Error = error{
    Mesh_Error,
};
pub fn SmallestMesh(
    // comptime back_dim: usize,
    // comptime dim: usize,
    comptime P: type,
    comptime VT: type,
    comptime CT: type,
    comptime MT: type,
) type {
    return struct {
        const Self = @This();
        // const CMesh=Mesh(P,VT,FT,HFT,CT,MT);
        points: [][]P = &.{},
        points_prop: []VT = &.{},
        // []CMesh.Vertex,

        data: union(enum) {
            simplex: struct {
                cells: [][]usize,
            },
            non_simplex: struct {
                halffaces: [][]usize,
                cells: [][]usize,
            },
        },
        cells_prop: []CT = &.{},
        // simplex: bool = true,

        dimension: u32 = 2,
        // Control delete operations and others
        manifold_require: bool = true,
        prop: MT = MT{},
        pub fn deinit(self: *Self, allocator: std.mem.Allocator) void {
            for (self.points) |point| {
                allocator.free(point);
            }
            allocator.free(self.points);
            allocator.free(self.points_prop);
            allocator.free(self.cells_prop);
            switch (self.data) {
                .simplex => {
                    for (self.data.simplex.cells) |cell| {
                        allocator.free(cell);
                    }
                    allocator.free(self.data.simplex.cells);
                },
                .non_simplex => {
                    for (self.data.non_simplex.halffaces) |halfface| {
                        allocator.free(halfface);
                    }
                    allocator.free(self.data.non_simplex.halffaces);
                    for (self.data.non_simplex.cells) |cell| {
                        allocator.free(cell);
                    }
                    allocator.free(self.data.non_simplex.cells);
                },
            }
        }
        pub fn isSimplex(self: Self) bool {
            return switch (self.data) {
                .simplex => true,
                .non_simplex => false,
            };
        }
        pub fn initSimplex(cells: [][]usize) Self {
            return Self{
                .points = undefined,
                .points_prop = undefined,
                .cells_prop = undefined,
                .data = .{ .simplex = .{ .cells = cells } },
            };
        }

        pub fn initNonSimplex(halffaces: [][]usize, cells: [][]usize) Self {
            return Self{
                .points = undefined,
                .points_prop = undefined,
                .cells_prop = undefined,
                .data = .{ .non_simplex = .{ .halffaces = halffaces, .cells = cells } },
            };
        }

        pub fn transfer(
            self: *Self,
            comptime FT: type,
            comptime HFT: type,
            allocator: std.mem.Allocator,
        ) !Mesh(P, VT, FT, HFT, CT, MT) {
            const CMesh = Mesh(P, VT, FT, HFT, CT, MT);
            var mesh = CMesh.init(allocator, MT{});
            mesh.dimension = self.dimension;
            mesh.manifold_require = self.manifold_require;
            mesh.simplex = self.isSimplex();
            var kv_slice = try allocator.alloc(
                rbtree.DefaultRBTree(i32, *CMesh.Vertex).KV,
                self.points.len,
            );
            defer allocator.free(kv_slice);

            for (self.points, self.points_prop, 0..) |point, point_prop, i| {
                const vertex: *CMesh.Vertex = try mesh.allocator.create(CMesh.Vertex);
                // vertex_init(re);
                vertex.init();
                vertex.id = @intCast(mesh.vertex_id);
                vertex.point = try allocator.alloc(P, point.len);
                @memmove(vertex.point, point);
                vertex.prop = point_prop;

                kv_slice[i] = .{ .key = vertex.id, .value = vertex };
                mesh.vertex_id += 1;
            }
            // rbtree.DefaultRBTree(i32, *Vertex)
            mesh.vertices = try rbtree.DefaultRBTree(i32, *CMesh.Vertex).initFromSortedKVSlice(
                allocator,
                {},
                kv_slice,
            );
            switch (self.data) {
                .simplex => |s| {
                    var temp_vertices: []*CMesh.Vertex = try allocator.alloc(*CMesh.Vertex, s.cells[0].len);
                    defer allocator.free(temp_vertices);
                    for (s.cells) |cell| {
                        for (0..cell.len) |i| {
                            temp_vertices[i] = kv_slice[cell[i]].value;
                        }
                        _ = mesh.create_cellv(temp_vertices);
                    }
                },
                .non_simplex => |nons| {
                    var max_hfsize: usize = 0;
                    for (nons.halffaces) |hfi| {
                        max_hfsize = if (hfi.len > max_hfsize) hfi.len else max_hfsize;
                    }

                    var temp_vertices = try allocator.alloc(*CMesh.Vertex, max_hfsize);
                    defer allocator.free(temp_vertices);

                    var kv_slice1 = try allocator.alloc(
                        rbtree.DefaultRBTree(i32, *CMesh.HalfFace).KV,
                        nons.halffaces.len,
                    );
                    defer allocator.free(kv_slice1);

                    for (nons.halffaces) |hfi| {
                        for (0..hfi.len) |i| {
                            temp_vertices[i] = kv_slice[hfi[i]].value;
                        }

                        const f = mesh.create_facev(temp_vertices[0..hfi.len]) orelse {
                            mesh.deinit();
                            return Mesh_Error.Mesh_Error;
                        };

                        if (f.halffaces[0].cell != null and f.halffaces[1].cell != null) {
                            mesh.deinit();
                            return Mesh_Error.Mesh_Error;
                        }

                        var hf: *CMesh.HalfFace = undefined;

                        if (f.halffaces[0].vertices.len == 0) {
                            hf = &(f.halffaces[0]);
                        } else if (f.halffaces[1].vertices.len == 0) {
                            hf = &(f.halffaces[1]);
                        } else {
                            if (f.halffaces[0].cell == null) {
                                hf = &(f.halffaces[0]);
                            } else if (f.halffaces[1].cell == null) {
                                hf = &(f.halffaces[1]);
                            } else {
                                // printf("流形的网格拓扑错误\n");
                                // for(int i=0;i<size;i++)
                                // {
                                //     printf("%d ",temp_v[i]->id);
                                // }
                                // printf("\n");
                                mesh.deinit();
                                return Mesh_Error.Mesh_Error;
                                // continue;
                            }
                        }

                        hf.id = @intCast(mesh.halfface_id);
                        mesh.halfface_id += 1;
                        if (hf.vertices.len == 0) {
                            hf.vertices = mesh.allocator.alloc(*CMesh.Vertex, hfi.len) catch &.{};
                        }
                        @memmove(hf.vertices, temp_vertices[0..hfi.len]);
                        kv_slice1[@intCast(hf.id)] = .{ .key = hf.id, .value = hf };
                    }
                    mesh.halffaces = try rbtree.DefaultRBTree(i32, *CMesh.HalfFace).initFromSortedKVSlice(
                        allocator,
                        {},
                        kv_slice1,
                    );
                    var max_cellsize: usize = 0;
                    for (nons.cells) |celli| {
                        max_cellsize = if (celli.len > max_hfsize) celli.len else max_hfsize;
                    }

                    var temp_hfs = try allocator.alloc(*CMesh.HalfFace, max_cellsize);
                    defer allocator.free(temp_hfs);

                    for (nons.cells) |celli| {
                        for (0..celli.len) |i| {
                            temp_hfs[i] = kv_slice1[celli[i]].value;
                        }
                        _ = mesh.create_cellf(temp_hfs[0..celli.len]);
                    }
                },
            }
            return mesh;
        }
    };
}

// pub fn Vertex(comptime P: type,comptime T:type) type {
//     return struct {
//         id: u32,
//         cells: std.ArrayListUnmanaged(T),
//         faces: std.ArrayListUnmanaged(T),
//         point: []P,
//         prop:T,
//     };
// }
// typedef struct Vertex {
//     LB_Vector1_voidptr cellsn;
//     LB_Vector1_voidptr facesn;
//     double *point;
//     void *prop;
//     int id;                     // 4 bytes
//     unsigned int point_size;    // 4 bytes

// #ifdef LIBCELL_USING_TRAITS
//     VertexT traits;             // Size depends on the actual type of VertexT
// #endif
// } Vertex;

// typedef struct HalfFace {
//     struct Vertex** vertices;  // 8 bytes
//     struct Cell* cell;         // 8 bytes
//     struct Face* face;         // 8 bytes
//     void *prop;                // 8 bytes
//     unsigned int vertices_size;// 4 bytes
//     int id;                    // 4 bytes

// #ifdef LIBCELL_USING_TRAITS
//     HalfT traits;              // Size depends on the actual type of HalfT
// #endif
// } HalfFace;

// typedef struct Face {
//     struct Vertex** vertices;
//     struct HalfFace* halffaces[2];
//     void *prop;

//     unsigned int vertices_size;
//     int id;

// #ifdef LIBCELL_USING_TRAITS
//     FaceT traits;
// #endif
// } Face;

// typedef struct Cell {
//     struct Vertex** vertices;
//     struct HalfFace** halffaces;
//     void *prop;

//     unsigned int vertices_size;
//     unsigned int halffaces_size;
//     int id;

// #ifdef LIBCELL_USING_TRAITS
//     CellT traits;
// #endif
// } Cell;
